﻿using LBSoft.Business;
using LBSoft.Common.DotNetBean;
using LBSoft.Common.DotNetCode;
using LBSoft.Common.DotNetConfig;
using LBSoft.Common.DotNetData;
using LBSoft.Common.DotNetExt;
using LBSoft.Common.DotNetFile;
using LBSoft.Common.DotNetImage;
using LBSoft.Common.DotNetJson;
using LBSoft.Common.DotNetOutExcel;
using LBSoft.Common.DotNetOutWord;
using LBSoft.Common.DotNetUI;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;

namespace LBSoft.HplusAdmin.Business.Person
{
    /// <summary>
    /// Person 的摘要说明
    /// </summary>
    public class Person : IHttpHandler
    {
        HttpContext con = null;
        mJsonResult json = new mJsonResult();
        Common_Dal systemidao = new Common_Dal();
        ExportExcelHelper eeh = new ExportExcelHelper();
        LogHelper log = new LogHelper();

        public void ProcessRequest(HttpContext context)
        {
            con = context;

            switch (con.Request["PostType"])
            {
                case "list": LoadList(); break;
                case "get": GetData(); break;
                case "set": SetData(); break;
                case "del": DelData(); break;
                case "Import": ImportData(); break;
                case "Export": ExportData(); break;
                case "upload": UploadData(); break;
            }
        }

        #region 列表
        private void LoadList()
        {
            switch (con.Request["ActionType"])
            {
                case "Person": LoadPersonList(); break; //人员列表
            }
        }

        /// <summary>
        /// 人员列表
        /// </summary>
        private void LoadPersonList()
        {
            int count = 0;
            int pageSize = con.Request["rows"].ToInt32(15);
            int curPage = con.Request["page"].ToInt32(1);

            IList<SqlParam> IList_param = new List<SqlParam>();
            StringBuilder SqlWhere = new StringBuilder(WebHelper.GetCondition(con.Request));
            SqlWhere.Append(" AND a.IsDelete=0 ");

            string tables = @" T_Person a ";
            string cols = @" a.* ";
            string orderStr = " CreateDate Desc ";

            DataTable dt = systemidao.GetListByPage(tables, cols, SqlWhere, orderStr, IList_param, curPage, pageSize, ref count);

            json.success = true;
            json.total = count;
            json.rows = dt;

            con.Response.Write(JsonConvert.SerializeObject(json));
        }
        #endregion

        #region 获取
        private void GetData()
        {
            switch (con.Request["ActionType"])
            {
                case "Person": GetPerson(); break; //获取人员
            }
        }

        /// <summary>
        /// 获取人员
        /// </summary>
        private void GetPerson()
        {
            string guid = con.Request["GUID"].ToString2();

            Hashtable ht = systemidao.GetDataByID("T_Person", "GUID", guid);

            con.Response.Write(JsonConvert.SerializeObject(ht));
        }
        #endregion

        #region  编辑
        private void SetData()
        {
            switch (con.Request["ActionType"])
            {
                case "Person": SetPerson(); break; //人员保存
            }
        }

        /// <summary>
        /// 人员保存
        /// </summary>
        private void SetPerson()
        {
            try
            {
                string userId = RequestSession.GetSessionUser().UserId;
                string userAccount = RequestSession.GetSessionUser().UserAccount;

                string guid = con.Request["GUID"].ToString2();
                string idCard = con.Request["IDCard"].ToString2();

                //重复身份证号不可添加
                DataTable dt = systemidao.GetDataTableBySQL(new StringBuilder($@"SELECT * FROM T_Person WHERE 1=1 AND IDCard='{idCard}' AND GUID!='{guid}'"));
                if (dt != null && dt.Rows.Count > 0)
                {
                    json.success = false;
                    json.msg = "已存在同身份证号人员，不可重复新增！";
                    con.Response.Write(JsonConvert.SerializeObject(json));
                    return;
                }

                Hashtable ht = systemidao.AddHashtable("T_Person", con);

                if (string.IsNullOrEmpty(guid))
                {
                    ht["IsDelete"] = 0;
                    ht["CreateDate"] = DateTime.Now;
                    ht["CreateUserId"] = userId;
                    ht["CreateAccount"] = userAccount;
                }
                else
                {
                    ht.Remove("IsDelete");
                    ht.Remove("CreateDate");
                    ht.Remove("CreateUserId");
                    ht.Remove("CreateAccount");
                    ht["ModifyDate"] = DateTime.Now;
                    ht["ModifyUserId"] = userId;
                    ht["ModifyAccount"] = userAccount;
                }

                //身份证头像处理-是否base64
                string imageUrl = con.Request["ImageUrl"].ToString2();
                string base64Header = "data:image/jpeg;base64,";
                if (imageUrl.IndexOf(base64Header) != -1)
                {
                    string base64Data = imageUrl.Replace(base64Header, "");
                    string PersonPicturePath = "/PersonPictures/";
                    string uploadPath = HttpContext.Current.Server.MapPath(PersonPicturePath);
                    if (!Directory.Exists(uploadPath))
                    {
                        Directory.CreateDirectory(uploadPath);
                    }
                    string newFileName = idCard + ".jpg";
                    string newFileUrl = "/PersonPictures/" + newFileName;

                    ImageHelper imageHelper = new ImageHelper();
                    imageHelper.Base64StringToImg(base64Data, uploadPath + newFileName, ImageFormat.Jpeg);

                    ht["ImageUrl"] = newFileUrl;
                }
                else
                {
                    //上传的照片重新覆盖
                    if (imageUrl.IndexOf("PersonPicturesTemp") != -1)
                    {
                        string sourceFileName = HttpContext.Current.Server.MapPath(imageUrl);
                        string newFileUrl = $"/PersonPictures/{idCard}.jpg";
                        string destFileName = HttpContext.Current.Server.MapPath(newFileUrl);

                        FileHelper.CopyFile(sourceFileName, destFileName, true);
                        ht["ImageUrl"] = newFileUrl;
                    }
                }

                bool result = systemidao.SubmitData("T_Person", "GUID", guid, ht);
                json.success = result;

                if (result)
                {
                    json.msg = "保存成功！";
                }
                else
                {
                    json.msg = "保存失败！";
                }
            }
            catch (Exception ex)
            {
                json.msg = ex.Message;
                log.WriteExceptionLog(ex);
            }

            con.Response.Write(JsonConvert.SerializeObject(json));
        }
        #endregion

        #region 删除
        private void DelData()
        {
            switch (con.Request["ActionType"])
            {
                case "Person": DelPerson(); break; //人员删除
            }
        }

        /// <summary>
        /// 人员删除
        /// </summary>
        private void DelPerson()
        {
            string guid = con.Request["GUID"].ToString2();

            if (string.IsNullOrEmpty(guid))
            {
                json.success = false;
                json.msg = "没有要删除的主键！";
                con.Response.Write(JsonConvert.SerializeObject(json));
                return;
            }

            List<string> list = guid.Split(',').ToList<string>();
            bool result = systemidao.BatchUpdateDeleteData("T_Person", "GUID", list.ToArray()) > 0;
            json.success = result;

            if (result)
            {
                json.msg = "删除成功！";
            }
            else
            {
                json.msg = "删除失败！";
            }

            con.Response.Write(JsonConvert.SerializeObject(json));
        }
        #endregion

        #region 导入
        private void ImportData()
        {
            switch (con.Request["ActionType"])
            {
                case "PersonPhoto": UploadPersonPhoto(); break;
            }
        }
        #endregion

        #region 导出
        private void ExportData()
        {
            switch (con.Request["ActionType"])
            {
                case "ExportPerson": ExportPerson(); break;
                case "ExportPerson2": ExportPerson2(); break;
                case "ExportPersonWord": ExportPersonWord(); break;
                case "ExportPersonPdf": ExportPersonPdf(); break;
            }
        }

        /// <summary>
        /// 导出
        /// </summary>
        private void ExportPerson()
        {
            try
            {
                string userType = RequestSession.GetSessionUser().UserType.ToString2();
                string userId = RequestSession.GetSessionUser().UserId.ToString2();
                StringBuilder SqlWhere = new StringBuilder(WebHelper.GetCondition(con.Request));

                DataTable dt = systemidao.GetDataTableBySQL(new StringBuilder($@"
                SELECT ROW_NUMBER() Over(order By a.CreateDate DESC) 序号
                ,a.PersonName 姓名,a.IDCard 身份证号,a.PersonSex 性别,a.PersonNation 民族,a.LinkPhone 联系电话
                FROM dbo.T_Person a
                {SqlWhere}"));

                string fileName = "人员信息" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
                string uploadPath = HttpContext.Current.Server.MapPath("~\\upfiles\\" + DateTime.Now.ToString("yyyyMMdd") + "\\");
                if (!Directory.Exists(uploadPath))
                {
                    Directory.CreateDirectory(uploadPath);
                }
                string filePath = uploadPath + fileName;
                eeh.GetExcel(dt, filePath, fileName);

                if (File.Exists(filePath))
                {
                    json.success = true;
                    json.msg = "导出成功！";
                    json.text = "\\upfiles\\" + DateTime.Now.ToString("yyyyMMdd") + "\\" + fileName;
                }
            }
            catch (Exception ex)
            {
                json.success = false;
                json.msg = "导出失败！";
                json.text = ex.Message;
            }

            con.Response.Write(JsonConvert.SerializeObject(json));
        }

        /// <summary>
        /// 导出复杂表头
        /// </summary>
        private void ExportPerson2()
        {
            try
            {
                string userType = RequestSession.GetSessionUser().UserType.ToString2();
                string userId = RequestSession.GetSessionUser().UserId.ToString2();
                StringBuilder SqlWhere = new StringBuilder(WebHelper.GetCondition(con.Request));

                DataTable dt = systemidao.GetDataTableBySQL(new StringBuilder($@"
                SELECT ROW_NUMBER() Over(order By a.CreateDate DESC) 序号
                ,a.PersonName 姓名,a.IDCard 身份证号,a.PersonSex 性别,a.PersonNation 民族,a.LinkPhone 联系电话
                FROM dbo.T_Person a
                {SqlWhere}"));

                string fileName = "人员信息2" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
                string uploadPath = HttpContext.Current.Server.MapPath("~\\upfiles\\" + DateTime.Now.ToString("yyyyMMdd") + "\\");
                if (!Directory.Exists(uploadPath))
                {
                    Directory.CreateDirectory(uploadPath);
                }
                string filePath = uploadPath + fileName;
                string excelTitle = "人员信息";

                DataSet ds = new DataSet();
                ds.Tables.Add(dt);
                eeh.GetExcel_ExportPerson2(ds, filePath, fileName, excelTitle);

                if (File.Exists(filePath))
                {
                    json.success = true;
                    json.msg = "导出成功！";
                    json.text = "\\upfiles\\" + DateTime.Now.ToString("yyyyMMdd") + "\\" + fileName;
                }
            }
            catch (Exception ex)
            {
                json.success = false;
                json.msg = "导出失败！";
                json.text = ex.Message;
            }

            con.Response.Write(JsonConvert.SerializeObject(json));
        }

        /// <summary>
        /// 导出Word
        /// </summary>
        private void ExportPersonWord()
        {
            try
            {
                string guid = con.Request["GUID"].ToString2();

                string uploadUrl = "/upfiles/" + DateTime.Now.ToString("yyyyMMdd") + "/";
                string fileName = guid + ".doc";
                string uploadPath = HttpContext.Current.Server.MapPath(uploadUrl);
                if (!Directory.Exists(uploadPath))
                {
                    Directory.CreateDirectory(uploadPath);
                }
                string filePath = uploadUrl + fileName;

                string softWebUrl = ConfigHelper.GetAppSettings("SoftWebUrl");

                string templateFileName = "人员信息模板.doc"; //模板文件名
                string filePath2 = "/WordTemplates/"; //模板路径
                string OutPdfName = fileName; //保存文件名
                string OutPath = uploadUrl; //保存路径

                DataTable dt = new DataTable();
                DataTable dtList = new DataTable();

                dt = systemidao.GetDataTableBySQL(new StringBuilder($@"SELECT *,'' BeginEndStr,'' ImageUrlStr FROM dbo.T_Person WHERE GUID='{guid}'"));
                dtList = systemidao.GetDataTableBySQL(new StringBuilder($@"SELECT a.* FROM dbo.T_Person a ORDER BY a.CreateDate DESC"));

                if (dt != null && dt.Rows.Count > 0)
                {
                    DataRow drFirst = dt.Rows[0];
                    string beginDate = drFirst["BeginDate"].ToDateTime().ToString("yyyy-MM-dd");
                    string endDate = drFirst["EndDate"].ToDateTime().ToString("yyyy-MM-dd");
                    string beginEndStr = $@"{beginDate} 至 {endDate}";
                    drFirst["BeginEndStr"] = beginEndStr;

                    string imageUrl = drFirst["ImageUrl"].ToString2();
                    if (!string.IsNullOrEmpty(imageUrl))
                    {
                        drFirst["ImageUrlStr"] = softWebUrl + imageUrl;
                    }
                }

                dt.TableName = "T1";
                dtList.TableName = "T2";

                DataSet ds = new DataSet();
                ds.Tables.Add(dt);
                ds.Tables.Add(dtList);

                //如果存在删除该文件
                if (File.Exists(con.Server.MapPath(OutPath + OutPdfName)))
                {
                    File.Delete(con.Server.MapPath(OutPath + OutPdfName));
                }
                WordPrint.WordPrintMethod2(filePath2, templateFileName, ds, OutPath + OutPdfName);

                json.success = true;
                json.text = filePath;
                json.msg = "导出成功！";
            }
            catch (Exception ex)
            {
                json.success = false;
                json.msg = "导出失败！";
                json.text = ex.Message;
            }

            con.Response.Write(JsonConvert.SerializeObject(json));
        }

        /// <summary>
        /// 导出PDF
        /// </summary>
        private void ExportPersonPdf()
        {
            try
            {
                string guid = con.Request["GUID"].ToString2();

                string uploadUrl = "/upfiles/" + DateTime.Now.ToString("yyyyMMdd") + "/";
                string fileName = guid + ".pdf";
                string uploadPath = HttpContext.Current.Server.MapPath(uploadUrl);
                if (!Directory.Exists(uploadPath))
                {
                    Directory.CreateDirectory(uploadPath);
                }
                string filePath = uploadUrl + fileName;

                string softWebUrl = ConfigHelper.GetAppSettings("SoftWebUrl");

                string templateFileName = "人员信息模板.doc"; //模板文件名
                string filePath2 = "/WordTemplates/"; //模板路径
                string OutPdfName = fileName; //保存文件名
                string OutPath = uploadUrl; //保存路径

                DataTable dt = new DataTable();
                DataTable dtList = new DataTable();

                dt = systemidao.GetDataTableBySQL(new StringBuilder($@"SELECT *,'' BeginEndStr,'' ImageUrlStr FROM dbo.T_Person WHERE GUID='{guid}'"));
                dtList = systemidao.GetDataTableBySQL(new StringBuilder($@"SELECT a.* FROM dbo.T_Person a ORDER BY a.CreateDate DESC"));

                if (dt != null && dt.Rows.Count > 0)
                {
                    DataRow drFirst = dt.Rows[0];
                    string beginDate = drFirst["BeginDate"].ToDateTime().ToString("yyyy-MM-dd");
                    string endDate = drFirst["EndDate"].ToDateTime().ToString("yyyy-MM-dd");
                    string beginEndStr = $@"{beginDate} 至 {endDate}";
                    drFirst["BeginEndStr"] = beginEndStr;

                    string imageUrl = drFirst["ImageUrl"].ToString2();
                    if (!string.IsNullOrEmpty(imageUrl))
                    {
                        drFirst["ImageUrlStr"] = softWebUrl + imageUrl;
                    }
                }

                dt.TableName = "T1";
                dtList.TableName = "T2";

                DataSet ds = new DataSet();
                ds.Tables.Add(dt);
                ds.Tables.Add(dtList);

                //如果存在删除该文件
                if (File.Exists(con.Server.MapPath(OutPath + OutPdfName)))
                {
                    File.Delete(con.Server.MapPath(OutPath + OutPdfName));
                }
                WordPrint.WordSavePdfMethod(filePath2 + templateFileName, ds, OutPath, OutPdfName);

                json.success = true;
                json.text = filePath;
                json.msg = "导出成功！";
            }
            catch (Exception ex)
            {
                json.success = false;
                json.msg = "导出失败！";
                json.text = ex.Message;
            }

            con.Response.Write(JsonConvert.SerializeObject(json));
        }
        #endregion

        #region 上传
        private void UploadData()
        {
            switch (con.Request["ActionType"])
            {
                case "PersonPhoto": UploadPersonPhoto(); break;
            }
        }

        /// <summary>
        /// 上传身份证头像
        /// </summary>
        private void UploadPersonPhoto()
        {
            string PersonPicturePath = "/PersonPictures/";
            string idCard = con.Request["IDCard"].ToString2();
            if (string.IsNullOrEmpty(idCard))
            {
                json.success = false;
                json.msg = "请先输入身份证号完善身份信息后再上传照片!";
                con.Response.Write(JsonConvert.SerializeObject(json));
                return;
            }

            HttpPostedFile file = con.Request.Files[0];

            if (!FileHelper.IsAllowedExtension(file))
            {
                json.success = false;
                json.msg = "检测到上传文件有问题!";
                con.Response.Write(JsonConvert.SerializeObject(json));
                return;
            }

            //if (file.ContentLength > 1024 * 50)
            //{
            //    json.success = false;
            //    json.msg = "只支持jpg、png、bmp图片格式且大小不得超过50KB!";
            //    con.Response.Write(JsonConvert.SerializeObject(json));
            //    return;
            //}
            string filename = file.FileName;
            string uploadPath = HttpContext.Current.Server.MapPath(PersonPicturePath);
            if (file != null)
            {
                if (!Directory.Exists(uploadPath))
                {
                    Directory.CreateDirectory(uploadPath);
                }
                Random ra = new Random();
                string fileExt = Path.GetExtension(file.FileName).ToLower();
                string newFileName = idCard + fileExt;

                file.SaveAs(uploadPath + newFileName);

                string filePath = PersonPicturePath + HttpUtility.UrlEncode(newFileName, System.Text.Encoding.UTF8);
                json.text = filePath;
                json.success = true;
            }
            con.Response.Write(JsonConvert.SerializeObject(json));
        }
        #endregion

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}